﻿using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Windows.Forms;

public static class HTTPManager
{
    public static string SendMessage(string prefix, string msg, Dictionary<string, string> headers)
    {
        if (prefix.Contains("127.0.0.1")) prefix = prefix.Replace("127.0.0.1", "localhost");
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("http://" + prefix, UriKind.Absolute));
        if (msg != null)
        {
            req.Method = "POST";
            StreamWriter writer = new StreamWriter(req.GetRequestStream());
            writer.WriteLine(msg);
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> h in headers)
                {
                    req.Headers.Add(h.Key, h.Value);
                }
            }
            writer.Flush();
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string str = reader.ReadToEnd();
            writer.Close();
            return str;
        }
        else
        {
            req.Method = "GET";
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> h in headers)
                {
                    req.Headers.Add(h.Key, h.Value);
                }
            }
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string data = reader.ReadToEnd();
            return data;
        }
    }

    public static HttpWebResponse SendMessage2(string prefix, string msg, Dictionary<string, string> headers)
    {
        if (prefix.Contains("127.0.0.1")) prefix = prefix.Replace("127.0.0.1", "localhost");
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("http://" + prefix, UriKind.Absolute));
        if (msg != null)
        {
            req.Method = "POST";
            StreamWriter writer = new StreamWriter(req.GetRequestStream());
            writer.WriteLine(msg);
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> h in headers)
                {
                    req.Headers.Add(h.Key, h.Value);
                }
            }
            writer.Flush();
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            return response;
        }
        else
        {
            req.Method = "GET";
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> h in headers)
                {
                    req.Headers.Add(h.Key, h.Value);
                }
            }
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            return response;
        }
    }
}